package com.demo.rpc.zk;

import org.apache.zookeeper.*;
import org.apache.zookeeper.data.Stat;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;
import java.nio.charset.StandardCharsets;

import static java.nio.charset.StandardCharsets.UTF_8;

public class ZkServer {
    private static final Logger LOGGER = LoggerFactory.getLogger(ZkServer.class);

    private int timeout;
    private String zkServers;
    private String serverPath;
    private String monitorServer;
    private ZooKeeper zk;
    private Watcher watcher;

    public ZkServer(String server, String zkServers, String serverPath) {
        this(server, zkServers, serverPath, 20000);
    }

    public ZkServer(String monitorServer, String zkServers, String serverPath, int timeout) {
        this.monitorServer = monitorServer;
        this.zkServers = zkServers;
        this.serverPath = serverPath;
        this.timeout = timeout;
        init();
    }


    private void init() {
        watcher = new Watcher() {
            @Override
            public void process(WatchedEvent event) {
                LOGGER.debug(event.getPath() + " : " + event.getType().name());
            }
        };
        try {
            zk = new ZooKeeper(zkServers, timeout, watcher);
            //查询服务器根节点
            Stat stat = zk.exists(serverPath, watcher);
            if (stat == null) {
                zk.create(serverPath, "rpcServeres".getBytes(UTF_8), ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
                LOGGER.debug("create znode:" + serverPath);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    //zookeeper注册服务器
    public void register() {
        try {
            zk.create(serverPath + "/rpcServer", monitorServer.getBytes(UTF_8), ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT_SEQUENTIAL);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    public String getMonitorServer() {
        return monitorServer;
    }
}
